<?php
/**
 * CreateTime: 2023/12/12 16:09
 * User:LinQ
 */

namespace App\Http\Service\Role;

use App\Facade\UserFuncFacade;
use App\Func\System\OperateLogFunc;
use App\Http\Service\BasicInterfaceService;
use App\Models\Auth\AuthModel;
use App\Models\Auth\RoleAuthModel;
use App\Models\Auth\RoleModel;
use App\Models\Auth\UserRoleModel;
use App\Models\Users\UsersModel;
use Illuminate\Support\Facades\DB;

class RoleService implements BasicInterfaceService  
{

    public function getList(array $prams)
    {
        $page_size = $prams['page_size'] ?? 10;
        $filters = $prams['filters'] ?? [];
        $desc = $prams['desc'] ?? [];
        $roleModel = new RoleModel();
        if($filters){
            $this->listSelectFilters($roleModel,$filters);
        }
        $res = $roleModel->cListHasCom($roleModel,$page_size,$desc);
        // 处理数据
        $res['data'] = $this->dispose($res['data']);
        s_c_return($res,trans('message.get_list_ok',[
            'name' => trans('key.role')
        ]));
    }

    public function dispose($data): mixed
    {
        return $data;
    }

    public function listSelectFilters($query, $filters)
    {
        $filters = trim_array($filters);
        if(map_has_value($filters,'role_name')){
            $query->pushFilter('role_name',$filters['role_name'],'like');
        }
    }

    public function bindAuth($data){
        $roleAuthMode = new RoleAuthModel();
        // 获取当前公司角色
        $roleModel = new RoleModel();
        $comId = UserFuncFacade::getCurrentComId();
        $roleId = $roleModel->select([
            'role_id'
        ])->where('com_id',$comId)
            ->where('role_id',$data['role_id'])
            ->first();
        if(!$roleId){
            s_fail_return(null,trans('message.bind_user_bad',[
                'code' => 1001
            ]));
        }
        // 获取当前公司的用户
        $authModel = new AuthModel();
        $authIds = $authModel->select('auth_id')->where('com_id',$comId)->whereIn('auth_id',$data['auth_ids'])->get();
        // 处理数据
        $insertData = [];
        foreach($authIds as $value){
            $insertData[] = [
                'auth_id' => $value['auth_id'],
                'role_id' => $data['role_id'],
                'auth_value' => 1,
                'created_at' => date('Y-m-d h:i:s')
            ];
        }
        DB::beginTransaction();
        try {
            $user_ids = array_column($insertData, 'user_id');
            $role_ids = array_column($insertData, 'role_id');
            $exists = $roleAuthMode
                ->whereIn('auth_id', $user_ids)
                ->whereIn('role_id', $role_ids)
                ->exists();
            if ($exists) {
                s_fail_return(null,trans('message.is_exists',[
                    'name' => trans('key.auth')
                ]));
            } else {
                $roleAuthMode->insert($insertData);
                DB::commit();
                s_c_return(null,trans('message.bind_role_ok'));
            }
        }catch (\Exception $exception){
            DB::rollBack();
            s_fail_return(null,trans('message.bind_role_bad',[
                'code' => 1002
            ]));
        }
    }

    public function bindUser(array $data)
    {
        $userRoleModel = new UserRoleModel();
        // 获取当前公司角色
        $roleModel = new RoleModel();
        $comId = UserFuncFacade::getCurrentComId();
        $roleId = $roleModel->select([
            'role_id'
        ])->where('com_id',$comId)
            ->where('role_id',$data['role_id'])
            ->first();
        if(!$roleId){
            s_fail_return(null,trans('message.bind_role_bad',[
                'code' => 1001
            ]));
        }
        // 获取当前公司的用户
        $userModel = new UsersModel();
        $userIds = $userModel->select('user_id')->where('com_id',$comId)->whereIn('user_id',$data['user_ids'])->get();
        // 处理数据
        $insertData = [];
        foreach($userIds as $value){
            $insertData[] = [
                'user_id' => $value['user_id'],
                'role_id' => $data['role_id'],
                'created_at' => date('Y-m-d h:i:s')
            ];
        }
        DB::beginTransaction();
        try {
            $user_ids = array_column($insertData, 'user_id');
            $role_ids = array_column($insertData, 'role_id');
            $exists = $userRoleModel
                ->whereIn('user_id', $user_ids)
                ->whereIn('role_id', $role_ids)
                ->exists();
            if ($exists) {
                s_fail_return(null,trans('message.is_exists',[
                    'name' => trans('key.role')
                ]));
            } else {
                $userRoleModel->insert($insertData);
                DB::commit();
                s_c_return(null,trans('message.bind_user_ok'));
            }
        }catch (\Exception $exception){
            DB::rollBack();
            s_fail_return(null,trans('message.bind_user_bad',[
                'code' => 1002
            ]));
        }
    }

    public function getSelect()
    {
        
    }

    public function getSelectHasPage($prams)
    {
        
    }

    public function getInfo($id)
    {
        
    }

    public function create($data)
    {
        $roleModel = new RoleModel();
        $userInfo =  UserFuncFacade::getLoginInfo();
        // 设置默认数据
        $insertData = [
            'role_name' => $data['role_name'],
            'com_id' => $userInfo['com_id'],
            'created_at' => date("Y-m-d h:i:s"),
            'updated_at' => date("Y-m-d h:i:s"),
        ];
        
        $res = $roleModel->insertGetId($insertData);

        // 添加操作记录
        OperateLogFunc::addOperate(
            'RoleService',$res,'create');

        s_c_return(['role_id'=>$res],trans('message.created_ok',[
            'name' => trans('key.role')
        ]));
    }

    public function fakeDelete($id)
    {

    }

    public function delete($id)
    {
        
    }

    public function update($data)
    {

    }

    public function fakeDeleteByIds($ids)
    {
        
    }
}